import {createSlice} from '@reduxjs/toolkit';
import {fetchNodesData} from '~/lib/directFetcher';

// 定义Node类型
export interface Node {
    id: string;
    name: string;

    [key: string]: any;
}

// 状态类型
interface NodesState {
    items: Node[];
    status: 'idle' | 'loading' | 'succeeded' | 'failed';
    error: string | null;
}

// 初始状态
const initialState: NodesState = {
    items: [],
    status: 'idle',
    error: null,
};

// 创建slice
const nodesSlice = createSlice({
    name: 'nodes',
    initialState,
    reducers: {
        // 手动更新nodes列表的reducer
        setNodes(state, action) {
            state.items = action.payload;
        },
        // 开始获取数据
        fetchNodesStart(state) {
            state.status = 'loading';
        },
        // 获取数据成功
        fetchNodesSuccess(state, action) {
            state.status = 'succeeded';
            state.items = action.payload;
        },
        // 获取数据失败
        fetchNodesFailed(state, action) {
            state.status = 'failed';
            state.error = action.payload || '获取节点失败';
        },
    },
});

// 导出actions
export const {
    setNodes,
    fetchNodesStart,
    fetchNodesSuccess,
    fetchNodesFailed
} = nodesSlice.actions;

// 创建异步fetchNodes函数
export const fetchNodes = () => async (dispatch: any) => {
    try {
        dispatch(fetchNodesStart());
        const response = await fetchNodesData();
        dispatch(fetchNodesSuccess(response || []));
    } catch (error) {
        dispatch(fetchNodesFailed(error instanceof Error ? error.message : '未知错误'));
    }
};

// 导出reducer
export default nodesSlice.reducer; 